package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.Result;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.POIUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestController
@RequestMapping("/report")
@Slf4j
public class ReportController {

    @Reference
    MemberService memberService;

    @Reference
    SetmealService setmealService;

    @Reference
    ReportService reportService;


    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        log.debug("运营数据统计！！");
        Map<String,Object> result = reportService.getBussinessReport();
        log.debug("result:"+result);
        return new Result(true,MessageConst.ACTION_SUCCESS, result );
    }

    @RequestMapping("/getMemberReport")
    public Result getMemberReport(@RequestParam String starttime,@RequestParam String endtime){
        log.debug("getMemberReport: 获取会员统计信息:"+starttime+"-"+endtime);
        Map<String, Object> map = memberService.getMemberReport(starttime,endtime);
        log.debug("MemberReport: " + map );

        log.debug("获取会员统计信息成功!!");
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }
    @RequestMapping("/getMemberReportBySex")
    public Result getMemberReportBySex(){
        log.debug("getMemberReport: 获取会员性别信息");
        List<String> sex = new ArrayList<>();
        List<Map<String, String>> memberCount = memberService.getMemberReportBySex();
        log.debug("memberCount: " + memberCount );
        if(memberCount != null && memberCount.size() > 0){
            for (Map<String, String> map : memberCount) {
                String name = map.get("name");
                sex.add(name);
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("sex",sex);
        resultMap.put("memberCount",memberCount);

        log.debug("MemberReport: " + resultMap );
        log.debug("获取会员统计信息成功!!");
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultMap);
    }

    @RequestMapping("/getMemberCountByAge")
    public Result getMemberCountByAge(){
        log.debug("getMemberReport: 获取会员年龄信息");
        List<String> age = new ArrayList<>();
        List<Map<String, String>> memberCount = memberService.getMemberCountByAge();
        log.debug("memberCount: " + memberCount );
        if(memberCount != null && memberCount.size() > 0){
            for (Map<String, String> map : memberCount) {
                String name = map.get("name");
                age.add(name);
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("age",age);
        resultMap.put("memberCount",memberCount);

        log.debug("MemberReport: " + resultMap );
        log.debug("获取会员统计信息成功!!");
        return new Result(true, MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS, resultMap);
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        log.debug("ReportController-getSetmealReport: 获取套餐统计信息");
        List<String> setmealNames = new ArrayList<>();//封装套餐名称集合
        List<Map> setmealCount = setmealService.getSetmealReport();//套餐名称和预约数量集合
        if(setmealCount != null && setmealCount.size() > 0){
            for (Map map : setmealCount) {
                String name = (String) map.get("name");//套餐名称
                setmealNames.add(name);
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);
        log.debug("getSetmealReport:" + map.toString());
        return new Result(true, MessageConst.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    /**
     * 1. 获取运营统计数据
     * 2. 创建模板对象
     * 3. 把数据写入模板中
     * 4. 下载excel到本地
     */
    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletResponse response){
        try {

//1. 获取运营统计数据
            Map<String, Object> businessReportData = reportService.getBussinessReport();
            //获取统计日期
            Object reportDate = businessReportData.get("reportDate");
            Object totalMember = businessReportData.get("totalMember");
            Object todayNewMember = businessReportData.get("todayNewMember");
            Object thisWeekNewMember = businessReportData.get("thisWeekNewMember");
            Object thisMonthNewMember = businessReportData.get("thisMonthNewMember");
            Object todayOrderNumber = businessReportData.get("todayOrderNumber");
            Object todayVisitsNumber = businessReportData.get("todayVisitsNumber");
            Object thisWeekOrderNumber = businessReportData.get("thisWeekOrderNumber");
            Object thisWeekVisitsNumber = businessReportData.get("thisWeekVisitsNumber");
            Object thisMonthOrderNumber = businessReportData.get("thisMonthOrderNumber");
            Object thisMonthVisitsNumber = businessReportData.get("thisMonthVisitsNumber");
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) businessReportData.get("hotSetmeal");

            //创建模板对象
            InputStream inputStream = this.getClass().getResourceAsStream("/template/report_template.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //把数据写入模板中
            //获取工作表对象（sheet）
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            //设置统计日期
            //获取行对象
            POIUtils.writeCell(sheet, 2, 5, reportDate);

            //设置今日新增会员数
            POIUtils.writeCell(sheet, 4, 5, todayNewMember);

            //设置总会员数
            POIUtils.writeCell(sheet, 4, 7, totalMember);

            //设置本周新增会员数
            POIUtils.writeCell(sheet, 5, 5, thisWeekNewMember);

            //设置本月新增会员数
            POIUtils.writeCell(sheet, 5, 7, thisMonthNewMember);


            //设置今日预约数
            POIUtils.writeCell(sheet, 7, 5, todayOrderNumber);

            //设置今日到诊数
            POIUtils.writeCell(sheet, 7, 7, todayVisitsNumber);

            //设置本周预约数
            POIUtils.writeCell(sheet, 8, 5, thisWeekOrderNumber);

            //设置本周到诊数
            POIUtils.writeCell(sheet, 8, 7, thisWeekVisitsNumber);

            //设置本月预约数
            POIUtils.writeCell(sheet, 9, 5, thisMonthOrderNumber);


            //设置本月到诊数
            POIUtils.writeCell(sheet, 9, 7, thisMonthVisitsNumber);

            //声明行号
            int rownum = 12;
            for (Map<String, Object> map : hotSetmeal) {
                POIUtils.writeCell(sheet, rownum, 4, map.get("name"));
                POIUtils.writeCell(sheet, rownum, 5, map.get("setmeal_count"));
                POIUtils.writeCell(sheet, rownum, 6, map.get("proportion"));

                rownum ++ ;
            }

            //下载excel到本地
            // 通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            //指定附件的格式为excel
            response.setContentType("application/vnd.ms-excel");
            //attachment 以附件下载
            //下载弹出框架中的默认的文件名
            response.setHeader("content-Disposition","attachment;filename="+reportDate+"_report.xlsx");
            //输出流下载
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessRuntimeException(MessageConst.GET_BUSINESS_REPORT_FAIL);
        }




    }
}
